package com.windystory.wslibrary.base.activity;

import android.annotation.SuppressLint;
import android.view.MenuItem;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomnavigation.LabelVisibilityMode;
import com.windystory.wslibrary.R;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * BaseBottomActivity
 */
public abstract class BaseBottomActivity extends BaseActivity {
    public BottomNavigationView bottomBar;
    private List<Fragment> fragmentList = new ArrayList<>();
    private ViewPageAdapter myViewPageAdapter;
    public ViewPager viewpager;
    //退出时间
    private long exitTime = 0;

    private int MAX_LIMIT_SIZE = 3;
    /**
     * 当前Fragment
     */
    private FragmentManager fm;

    @Override
    public int getLayoutRes() {
        return R.layout.activity_base_bottom;
    }

    @Override
    protected void initView() {
        bottomBar = (BottomNavigationView) findViewById(R.id.navigationViewEx);
        viewpager = (ViewPager) findViewById(R.id.functions);
    }

    @Override
    protected void initData() {
        Objects.requireNonNull(getSupportActionBar()).hide();
        fm = getSupportFragmentManager();
        bottomBar.inflateMenu(getMenuRes());
        bottomBar.setItemIconTintList(null);
        //添加Tab页
        fragmentList.addAll(initTab());
        myViewPageAdapter = new ViewPageAdapter(getSupportFragmentManager(), fragmentList);
        viewpager.setAdapter(myViewPageAdapter);
        viewpager.setOffscreenPageLimit(MAX_LIMIT_SIZE);
        //添加Menu ID
        initTabListener(initMenuRes());
        //设置默认项
        bottomBar.setSelectedItemId(bottomBar.getMenu().getItem(0).getItemId());
        bottomBar.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
        disableShiftingMode(bottomBar);
        disableItemScale(bottomBar);
        initItem();
    }

    /**
     * 其他初始化
     */
    protected abstract void initItem();

    /**
     * 初始化Menu
     */
    protected abstract List<Integer> initMenuRes();

    @Override
    protected void initListener() {
    }

    /**
     * Tab页点击
     *
     * @param Res Menu的R资源ID
     */
    protected void initTabListener(final List<Integer> Res) {

        bottomBar.setOnNavigationItemSelectedListener(menuItem -> {
            setStatusAndColor(Res, menuItem);
            return true;
        });


        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                bottomBar.setSelectedItemId(bottomBar.getMenu().getItem(i).getItemId());
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }



    /**
     * 填充菜单
     *
     * @return
     */
    protected abstract int getMenuRes();

    /**
     * 初始化Tab页面
     */
    protected abstract List<Fragment> initTab();


    /**
     * ViewPager的适配器
     */
    public class ViewPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;

        public ViewPageAdapter(FragmentManager fm, List<Fragment> fragmentList) {
            super(fm);
            this.fragmentList = fragmentList;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

    }

    /**
     * 退出App
     *
     * @param tips 提示信息
     */
    public void twicePress2ExitApp(String tips) {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            showToast(tips);
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    @SuppressLint("RestrictedApi")
    public static void disableShiftingMode(BottomNavigationView view) {
        try {
            BottomNavigationMenuView mMenuView = (BottomNavigationMenuView) view.getChildAt(0);
            Field mShiftingModeField = BottomNavigationMenuView.class.getDeclaredField("mShiftingMode");
            mShiftingModeField.setAccessible(true);
            mShiftingModeField.set(mMenuView, false);
            for (int i = 0; i < mMenuView.getChildCount(); i++) {
                BottomNavigationItemView itemView = (BottomNavigationItemView) mMenuView.getChildAt(i);
                itemView.setShifting(false);
                itemView.setChecked(itemView.getItemData().isChecked());
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
        }
    }

    @SuppressLint("RestrictedApi")
    public static void disableItemScale(BottomNavigationView view) {
        try {
            BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
            Field mLargeLabelField = BottomNavigationItemView.class.getDeclaredField("mLargeLabel");
            Field mSmallLabelField = BottomNavigationItemView.class.getDeclaredField("mSmallLabel");
            Field mShiftAmountField = BottomNavigationItemView.class.getDeclaredField("mShiftAmount");
            Field mScaleUpFactorField = BottomNavigationItemView.class.getDeclaredField("mScaleUpFactor");
            Field mScaleDownFactorField = BottomNavigationItemView.class.getDeclaredField("mScaleDownFactor");
            mSmallLabelField.setAccessible(true);
            mLargeLabelField.setAccessible(true);
            mShiftAmountField.setAccessible(true);
            mScaleUpFactorField.setAccessible(true);
            mScaleDownFactorField.setAccessible(true);
            final float fontScale = view.getResources().getDisplayMetrics().scaledDensity;
            for (int i = 0; i < menuView.getChildCount(); i++) {
                BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(i);
                TextView lagerObj = (TextView) mLargeLabelField.get(itemView);
                TextView smallObj = (TextView) mSmallLabelField.get(itemView);
                lagerObj.setTextSize(smallObj.getTextSize() / fontScale + 0.5f);
                mShiftAmountField.set(itemView, 0);
                mScaleUpFactorField.set(itemView, 1f);
                mScaleDownFactorField.set(itemView, 1f);
                itemView.setChecked(itemView.getItemData().isChecked());
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
        }
    }


    /**
     * 设置默认颜色与图标状态
     * 设置点击bottombar颜色
     *
     * @param Res      Menu的R资源ID
     * @param menuItem menuItem
     */
    private void setStatusAndColor(List<Integer> Res, MenuItem menuItem) {
        for (int i = 0; i < Res.size(); i++) {
            if (menuItem.getItemId() == Res.get(i)) {
                viewpager.setCurrentItem(i);
            } else {
            }
        }
    }

}
